<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Browser</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        a {
            text-decoration: none;
            color: #0066cc;
        }
        a:hover {
            text-decoration: underline;
        }
        .dir {
            font-weight: bold;
        }
        .file {
            color: #666;
        }
    </style>
</head>
<body>
    <h1>File Browser</h1>
    <div id="current-path"></div>
    <table id="file-table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Size</th>
                <th>Modified</th>
            </tr>
        </thead>
        <tbody id="file-list">
            <!-- Files will be listed here -->
        </tbody>
    </table>

    <script>
        const API_BASE_URL = 'http://127.0.0.1:8080/static';
        // Track navigation state - always start at root
        let currentDir = '/';

        // Format file size
        function formatSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // Format date
        function formatDate(timestamp) {
            return new Date(timestamp).toLocaleString();
        }

        // Load directory contents
        async function loadDirectory(dir) {
            try {
                const response = await fetch(`${API_BASE_URL}/dirinfo?dir=${encodeURIComponent(dir)}`);
                if (!response.ok) {
                    throw new Error('Failed to load directory');
                }
                const files = await response.json();
                
                // Update current directory display
                document.getElementById('current-path').textContent = `Current Path: ${dir}`;
                
                // Clear existing files
                const fileList = document.getElementById('file-list');
                fileList.innerHTML = '';
                
                // Add parent directory link if not at root
                if (dir !== '/') {
                    const parentDir = dir.split('/').slice(0, -2).join('/') + '/';
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td><a href="#" class="dir" data-dir="${parentDir}">..</a></td>
                        <td>-</td>
                        <td>-</td>
                    `;
                    fileList.appendChild(row);
                }
                
                // Separate and sort directories and files
                const dirs = files.filter(file => file.isDirectory)
                               .sort((a, b) => a.name.localeCompare(b.name));
                const fileItems = files.filter(file => !file.isDirectory)
                                 .sort((a, b) => a.name.localeCompare(b.name));
                
                // Combine with directories first
                const sortedFiles = [...dirs, ...fileItems];
                
                // Add files and directories to table
                sortedFiles.forEach(file => {
                    const row = document.createElement('tr');
                    if (file.isDirectory) {
                        row.innerHTML = `
                            <td><a href="#" class="dir" data-dir="${dir}${file.name}/">${file.name}/</a></td>
                            <td>-</td>
                            <td>${formatDate(file.modified)}</td>
                        `;
                    } else {
                        row.innerHTML = `
                            <td><a href="${API_BASE_URL}/download/${encodeURIComponent(file.name)}?dir=${encodeURIComponent(dir)}" class="file">${file.name}</a></td>
                            <td>${formatSize(file.size)}</td>
                            <td>${formatDate(file.modified)}</td>
                        `;
                    }
                    fileList.appendChild(row);
                });
                
                // Update current directory
                currentDir = dir;
            } catch (error) {
                console.error('Error:', error);
                alert('Failed to load directory: ' + error.message);
            }
        }

        // Handle directory navigation
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('dir')) {
                e.preventDefault();
                const dir = e.target.getAttribute('data-dir');
                loadDirectory(dir);
            }
        });

        // Always load root directory when page first opens
        window.addEventListener('load', () => {
            // Reset to root and load
            currentDir = '/';
            loadDirectory(currentDir);
            
            // Update browser history with root path
            window.history.replaceState({dir: currentDir}, '', window.location.pathname);
        });
    </script>
</body>
</html>